package net.zjitc.controller;

import net.zjitc.pojo.CategorySecond;
import net.zjitc.pojo.Product;
import net.zjitc.service.CategorySecondService;
import net.zjitc.service.ProductService;
import net.zjitc.service.impl.CategorySecondServiceImpl;
import net.zjitc.service.impl.ProductServiceImpl;
import net.zjitc.utils.PageBean;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/11/22.
 */
public class AdminProduct {
    ProductService productService = new ProductServiceImpl();
    CategorySecondService secondService = new CategorySecondServiceImpl();
    //显示列表
    @URLMapping(url = "/AdminProductFindALL")
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        int page = 1;
        int pageSize = 12;
        PageBean<Product> pageBean = productService.findPageBean(page,pageSize);
        request.setAttribute("page",pageBean);
        return "/admin/product/list.jsp" ;
    }

    //显示添加页面
    @URLMapping(url = "/AdminProductAddUI")
    public String addUI(HttpServletRequest request, HttpServletResponse response){
        List<CategorySecond> list=secondService.findAll();
        request.setAttribute("list",list);
        return "/admin/product/addUI.jsp" ;
    }

    //添加功能
    @URLMapping(url = "/AdminProductAdd")
    public String add(HttpServletRequest request, HttpServletResponse response){
        //创建一个工厂
        DiskFileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload fileUpload=new ServletFileUpload(factory);
        fileUpload.setHeaderEncoding("utf-8");
        Product product=new Product();
        CategorySecond categorySecond=new CategorySecond();
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem item : fileItems) {
                    if (item.isFormField()) {
                        if ("pname".equals(item.getFieldName())){
                            product.setPname(item.getString("utf-8"));
                        }
                        if ("shopPrice".equals(item.getFieldName())){
                            product.setShop_price(Double.valueOf(item.getString()));
                        }
                        if ("marketPrice".equals(item.getFieldName())){
                            product.setMarket_price(Double.valueOf(item.getString()));
                        }
                        if ("isHot".equals(item.getFieldName())){
                            product.setIs_hot(Integer.valueOf(item.getString()));
                        }
                        if ("pdesc".equals(item.getFieldName())){
                            product.setPdesc(item.getString("utf-8"));
                        }
                        if ("csid".equals(item.getFieldName())){
                           categorySecond.setCsid(Integer.valueOf(item.getString()));
                           product.setCategorySecond(categorySecond);
                        }
                    }
                    else {
                        //处理文件
                        //文件的输入流 文件名可能一样
                        String fileName=item.getName();
                        InputStream inputStream=item.getInputStream();
                        //输入流保存到本地
                        String path=request.getServletContext().getRealPath("/product/5");
                        File dir=new File(path);
                        if (!dir.exists()){
                            dir.mkdirs();
                        }
                        File file=new File(dir,fileName);
                        item.write(file);
                        //保存到数据库中的路径
                        String imgPath="product/5/"+fileName;
                        product.setImage(imgPath);
                    }
                }
                product.setPdate(new Date());

            } catch (Exception e) {
                e.printStackTrace();
            }

            int count=productService.insert(product);
        //添加完后，要重定向到。。。。。
        String url = request.getContextPath()+"/AdminProductFindALL";
        String url1 =request.getContextPath()+"/AdminProductFindALL?page=1";
        return "Redirect:"+url ;
    }

    //显示修改页面
    @URLMapping(url = "/AdminProductEditUI")
    public String editUI(HttpServletRequest request, HttpServletResponse response){
        List<CategorySecond> list=secondService.findAll();
        request.setAttribute("list",list);
        int pid = Integer.parseInt(request.getParameter("pid"));
        Product product = productService.selectProduct(pid);
        request.setAttribute("p", product);
        return "/admin/product/editUI.jsp";
    }

    //更新功能
    @URLMapping(url = "/AdminProductEdit")
    public String edit(HttpServletRequest request, HttpServletResponse response){

        //创建一个工厂
        DiskFileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload fileUpload=new ServletFileUpload(factory);
        fileUpload.setHeaderEncoding("utf-8");
        Product product=new Product();
        CategorySecond categorySecond=new CategorySecond();
        try {
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem item : fileItems) {
                if (item.isFormField()) {
                    if ("pid".equals(item.getFieldName())){
                        product.setPid(Integer.parseInt(item.getString("utf-8")));
                    }
                    if ("pname".equals(item.getFieldName())){
                        product.setPname(item.getString("utf-8"));
                    }
                    if ("shopPrice".equals(item.getFieldName())){
                        product.setShop_price(Double.valueOf(item.getString()));
                    }
                    if ("marketPrice".equals(item.getFieldName())){
                        product.setMarket_price(Double.valueOf(item.getString()));
                    }
                    if ("isHot".equals(item.getFieldName())){
                        product.setIs_hot(Integer.valueOf(item.getString()));
                    }
                    if ("pdesc".equals(item.getFieldName())){
                        product.setPdesc(item.getString("utf-8"));
                    }
                    if ("csid".equals(item.getFieldName())){
                        categorySecond.setCsid(Integer.valueOf(item.getString()));
                        product.setCategorySecond(categorySecond);
                    }
                }
                else {
                    //处理文件
                    //文件的输入流 文件名可能一样
                    String fileName=item.getName();
                    InputStream inputStream=item.getInputStream();
                    //输入流保存到本地
                    String path=request.getServletContext().getRealPath("/product/5");
                    File dir=new File(path);
                    if (!dir.exists()){
                        dir.mkdirs();
                    }
                    File file=new File(dir,fileName);
                    item.write(file);
                    //保存到数据库中的路径
                    String imgPath="product/5/"+fileName;
                    product.setImage(imgPath);
                }
            }
            product.setPdate(new Date());

        } catch (Exception e) {
            e.printStackTrace();
        }
        productService.update(product);
        String url = request.getContextPath()+"/AdminProductFindALL";
        return "Redirect:"+url ;
    }

    //删除功能
    @URLMapping(url = "/AdminProductDelete")
    public String delete(HttpServletRequest request, HttpServletResponse response){

        //删除完后，要重定向到。。。。。
        int pid = Integer.parseInt(request.getParameter("pid"));
        productService.delete(pid);

        String url = request.getContextPath()+"/AdminProductFindALL";
        return "Redirect:"+url ;
    }
}
